<template>
  <view class="container">
    <!-- 入库订单列表区域 -->
    <view class="order-list-section">
      <view class="section-header">
        <text class="section-title">入库记录</text>
      </view>

      <!-- 添加订单标签页，与出库页面保持一致 -->
      <uv-subsection
        :list="['全部', '已支付', '未支付']"
        :current="isPaidFilterIndex"
        mode="button"
        @change="onIsPaidFilterChange"
      ></uv-subsection>

      <!-- 筛选区域 -->
      <uv-collapse>
        <uv-collapse-item title="条件筛选">
          <view class="filter-area">
            <!-- 厂商筛选 -->
            <view class="filter-group">
              <view class="filter-title">厂商筛选</view>
              <picker
                :range="manufacturers"
                :value="manufacturerFilterIndex"
                @change="onManufacturerFilterChange"
                class="filter-picker"
              >
                <view class="picker-text">
                  {{ manufacturers[manufacturerFilterIndex] }}
                </view>
              </picker>
            </view>

            <!-- 规格筛选 -->
            <view class="filter-group">
              <view class="filter-title">规格筛选</view>
              <picker
                :range="specifications"
                :value="specificationFilterIndex"
                @change="onSpecificationFilterChange"
                class="filter-picker"
              >
                <view class="picker-text">
                  {{ specifications[specificationFilterIndex] }}
                </view>
              </picker>
            </view>

            <view class="filter-group date-filter">
              <view class="filter-title">日期范围</view>
              <view class="date-range">
                <picker
                  mode="date"
                  :value="startDate"
                  @change="onStartDateChange"
                  class="filter-picker"
                >
                  <view class="picker-text">{{ startDate || "开始日期" }}</view>
                </picker>
                <text class="date-separator">至</text>
                <picker
                  mode="date"
                  :value="endDate"
                  @change="onEndDateChange"
                  class="filter-picker"
                >
                  <view class="picker-text">{{ endDate || "结束日期" }}</view>
                </picker>
              </view>
            </view>

            <view class="filter-group">
              <view class="filter-title">单价范围 (元/吨)</view>
              <view class="price-range">
                <input
                  type="number"
                  class="price-input"
                  placeholder="最小"
                  v-model="minPrice"
                />
                <text class="range-separator">-</text>
                <input
                  type="number"
                  class="price-input"
                  placeholder="最大"
                  v-model="maxPrice"
                />
              </view>
            </view>

            <view class="filter-group">
              <view class="filter-title">总价范围 (元)</view>
              <view class="price-range">
                <input
                  type="number"
                  class="price-input"
                  placeholder="最小"
                  v-model="minTotalAmount"
                />
                <text class="range-separator">-</text>
                <input
                  type="number"
                  class="price-input"
                  placeholder="最大"
                  v-model="maxTotalAmount"
                />
              </view>
            </view>

            <view class="filter-actions">
              <button class="filter-btn" @click="onSubmit">筛选</button>
              <button class="reset-btn" @click="onReset">重置</button>
            </view>
          </view>
        </uv-collapse-item>
      </uv-collapse>

      <!-- 订单列表 -->
      <scroll-view
        class="order-list-scroll"
        scroll-y
        @scrolltolower="loadMore"
        :style="{ height: scrollViewHeight + 'px' }"
        refresher-enabled
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
        refresher-background="#f2f2f2"
      >
        <view class="order-list">
          <uni-card
            v-for="(item, index) in inStockList"
            :key="index"
            margin="10px 0"
            padding="10px"
            @click="goToDetails(item._id)"
          >
            <view class="order-header">
              <text class="order-date">{{ item.date }}</text>
              <text class="order-price">¥{{ item.totalAmount }}</text>
            </view>
            <view class="order-content">
              <!-- 修改：添加商品信息显示 -->
              <view class="product-info">
                <text class="product-name">{{ item.manufacturer }}</text>
                <text class="product-spec">{{ item.specification }}</text>
              </view>
              <view class="order-info">
                <text class="info-item">数量：{{ item.quantity }}吨</text>
                <text class="info-item">单价：¥{{ item.price }}/吨</text>
              </view>

              <!-- 添加：支付信息 -->
              <view class="payment-info">
                <text class="payment-item"
                  >已付金额：¥{{ item.paidAmount }}</text
                >
                <text
                  :class="[
                    'payment-item',
                    item.remainingAmount > 0
                      ? 'remaining-amount'
                      : 'amount-zero',
                  ]"
                >
                  剩余金额：¥{{ item.remainingAmount }}
                </text>
                <text class="payment-item">
                  状态：
                  <text
                    :style="{
                      color: item.isPaid ? '#67c23a' : '#f56c6c',
                    }"
                  >
                    {{ item.isPaid ? "已支付" : "未支付" }}
                  </text>
                </text>
              </view>

              <!-- 添加：备注信息 -->
              <view v-if="item.remark" class="order-remark">
                备注：{{ item.remark }}
              </view>

              <!-- 添加：支付操作按钮 -->
              <view v-if="item.isPaid" class="action-buttons-row">
                <button class="pay-btn" @click="openPaymentDialog(item)">
                  添加付款
                </button>
                <button class="mark-btn" @click="markAsPaid(item.id)">
                  标记已付
                </button>
              </view>
            </view>
          </uni-card>

          <!-- 加载更多提示 -->
          <view v-if="!isListEmpty" class="load-more">
            <text v-if="isLoading" class="loading-text">加载中...</text>
            <text v-else-if="!hasMore" class="no-more-text"
              >没有更多数据了</text
            >
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 添加：付款弹窗 -->
    <uni-popup ref="paymentPopup" type="dialog">
      <view class="payment-dialog">
        <view class="dialog-title">添加付款</view>
        <view class="payment-summary">
          <text class="summary-item">
            订单总额：<text class="highlight"
              >¥{{ currentOrder.totalAmount }}</text
            >
          </text>
          <text class="summary-item">
            已付金额：<text class="highlight"
              >¥{{ currentOrder.paidAmount }}</text
            >
          </text>
          <text class="summary-item">
            剩余金额：<text class="highlight"
              >¥{{ currentOrder.remainingAmount }}</text
            >
          </text>
        </view>
        <view class="payment-input-area">
          <text class="payment-label">付款金额：</text>
          <input
            type="number"
            v-model="paymentAmount"
            class="payment-input"
            placeholder="请输入付款金额"
          />
        </view>
        <view class="dialog-buttons">
          <button class="cancel-btn" @click="closePaymentDialog">取消</button>
          <button class="confirm-btn" @click="confirmPayment">确认</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from "vue";
const uniCloudInStockManager = uniCloud.importObject("inStockManager");
// 厂商和规格数据
const manufacturers = [
  "全部",
  "虎狮水泥",
  "明狮水泥",
  "万年水泥",
  "豪福水泥",
  "红狮水泥",
];
const specifications = ["全部", "325", "325R", "425", "425R"];

// 是否支付
const isPaidFilterIndex = ref(0);
// 水泥厂商
const manufacturerFilterIndex = ref(0);
// 水泥规格
const specificationFilterIndex = ref(0);

// 筛选条件
const startDate = ref("");
const endDate = ref("");
const minPrice = ref(undefined);
const maxPrice = ref(undefined);
const minTotalAmount = ref(undefined);
const maxTotalAmount = ref(undefined);

// 下拉刷新相关
const isRefreshing = ref(false);
const refreshStartY = ref(0);
const scrollViewHeight = ref(500); // 默认高度，会在onMounted中计算

// 分页加载相关
const pageSize = ref(2); // 每页加载的数据量
const currentPage = ref(1);
const hasMore = ref(true);
const isLoading = ref(false);

// 添加：付款相关
const currentOrder = ref({});
const paymentAmount = ref("");

// 添加：弹窗引用
const paymentPopup = ref(null);

// 修改：入库订单数据
const inStockList = reactive([]);

// 计算列表是否为空
const isListEmpty = computed(() => {
  return inStockList.length === 0;
});
// 筛选器变更处理
function onIsPaidFilterChange(index) {
  isPaidFilterIndex.value = index;
  currentPage.value = 1;
  fetchData(true);
}

// 筛选器变更处理
function onManufacturerFilterChange(e) {
  manufacturerFilterIndex.value = Number(e.detail.value);
}

function onSpecificationFilterChange(e) {
  specificationFilterIndex.value = Number(e.detail.value);
}

// 日期筛选事件处理
function onStartDateChange(e) {
  startDate.value = e.detail.value;
}

function onEndDateChange(e) {
  endDate.value = e.detail.value;
}

// 应用筛选
function onSubmit() {
  currentPage.value = 1; // 重置分页
  fetchData();
}

function onReset() {
  startDate.value = "";
  endDate.value = "";
  minPrice.value = "";
  maxPrice.value = "";
  minTotalAmount.value = "";
  maxTotalAmount.value = "";
  manufacturerFilterIndex.value = 0;
  specificationFilterIndex.value = 0;
  currentPage.value = 1; // 重置分页
  fetchData();
}
// 重置筛选条件

// 刷新数据
async function onRefresh() {
  isRefreshing.value = true;
  // 重置分页
  currentPage.value = 1;
  hasMore.value = true;
  // 这里可以调用API刷新数据
  try {
    await fetchData(true);
  } catch (error) {
    console.error("刷新数据失败:", error);
  } finally {
    // 延迟结束刷新状态，提供更好的用户体验
    isRefreshing.value = false;
  }
}

// 加载更多数据
async function loadMore() {
  if (isLoading.value || !hasMore.value) return;
  isLoading.value = true;
  try {
    // 增加页数
    currentPage.value += 1;
    // 获取下一页数据
    await fetchData();
  } catch (error) {
    console.error("加载更多数据失败:", error);
  } finally {
    isLoading.value = false;
  }
}

// 获取数据函数
async function fetchData(isRefresh = false) {
  try {
    // 显示加载中
    isLoading.value = true;
    // 构建筛选参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      //是否支付
      isPaid:
        isPaidFilterIndex.value > 0 ? isPaidFilterIndex.value === 1 : undefined,
      //厂商
      manufacturer:
        manufacturerFilterIndex.value > 0
          ? manufacturers[manufacturerFilterIndex.value]
          : undefined,
      //规格
      specification:
        specificationFilterIndex.value > 0
          ? specifications[specificationFilterIndex.value]
          : undefined,

      // 日期范围
      date: {
        $gte: startDate?.value || undefined,
        $lte: endDate?.value || undefined,
      },

      // 价格范围
      price: {
        $gte: minPrice.value ? Number(minPrice.value) : undefined,
        $lte: maxPrice.value ? Number(maxPrice.value) : undefined,
      },
      // 总金额范围
      totalAmount: {
        $gte: minTotalAmount.value ? Number(minTotalAmount.value) : undefined,
        $lte: maxTotalAmount.value ? Number(maxTotalAmount.value) : undefined,
      },
    };

    // 调用云函数获取数据
    const { code, data, total } = await uniCloudInStockManager.getInStockList(
      params
    );

    // 处理返回数据
    if (code === 0) {
      // 如果是刷新或第一页，替换数据
      if (isRefresh || currentPage.value === 1) {
        inStockList.splice(0, inStockList.length, ...data);
      } else {
        // 否则添加到现有数据
        inStockList.push(...data);
      }
      console.log(inStockList);
      // 更新是否有更多数据
      hasMore.value = inStockList.length < total;
    }
  } catch (error) {
    console.log(error);
    uni.showToast({
      title: "获取数据失败",
      icon: "none",
    });
  } finally {
    isLoading.value = false;
  }
}

// 计算滚动视图高度
function calculateScrollViewHeight() {
  // 使用uni-app API获取窗口高度
  uni.getSystemInfo({
    success: (res) => {
      // 假设订单列表上方的内容高度总共约为320px
      // 这个值需要根据实际情况调整
      const topContentHeight = 320;
      scrollViewHeight.value = res.windowHeight - topContentHeight;
    },
  });
}

onMounted(() => {
  // 初始化时获取第一页数据
  fetchData(true);

  // 计算滚动视图高度
  calculateScrollViewHeight();

  // 计算其他初始化逻辑...
});

// 添加：打开付款弹窗
function openPaymentDialog(order) {
  currentOrder.value = order;
  paymentAmount.value = "";
  paymentPopup.value.open();
}

// 添加：关闭付款弹窗
function closePaymentDialog() {
  paymentPopup.value.close();
}

// 添加：确认付款
async function confirmPayment() {
  const payAmount = Number(paymentAmount.value);
  if (isNaN(payAmount) || payAmount <= 0) {
    uni.showToast({
      title: "请输入有效的付款金额",
      icon: "none",
    });
    return;
  }

  if (payAmount > currentOrder.value.remainingAmount) {
    uni.showToast({
      title: "付款金额不能超过剩余金额",
      icon: "none",
    });
    return;
  }

  try {
    uni.showLoading({ title: "处理中..." });

    // 计算新的已付金额
    const newPaidAmount = currentOrder.value.paidAmount + payAmount;
    const totalAmount = currentOrder.value.totalAmount;

    // 调用云函数更新数据
    await uniCloudInStockManager.updateInventory(currentOrder.value.id, {
      paidAmount: newPaidAmount,
      // 云函数会自动处理remainingAmount, isPaid和paidTime
    });

    // 更新本地数据
    const orderIndex = inStockList.findIndex(
      (item) => item.id === currentOrder.value.id
    );
    if (orderIndex !== -1) {
      const newRemainingAmount = totalAmount - newPaidAmount;
      inStockList[orderIndex].paidAmount = newPaidAmount;
      inStockList[orderIndex].remainingAmount = newRemainingAmount;
      inStockList[orderIndex].isPaid =
        newRemainingAmount <= 0 ? "已支付" : "未支付";

      uni.showToast({
        title: "付款成功",
        icon: "success",
      });
    }

    paymentPopup.value.close();
  } catch (error) {
    console.error("付款失败:", error);
    uni.showToast({
      title: "付款操作失败",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
}

// 添加：标记为已支付
async function markAsPaid(orderId) {
  try {
    uni.showLoading({ title: "处理中..." });

    const orderIndex = inStockList.findIndex((item) => item.id === orderId);
    if (orderIndex !== -1) {
      // 调用云函数更新数据
      await uniCloudInStockManager.updateInventory(orderId, {
        paidAmount: inStockList[orderIndex].totalAmount,
        isPaid: true,
        // 云函数会自动设置remainingAmount=0和paidTime
      });

      // 更新本地数据
      inStockList[orderIndex].paidAmount = inStockList[orderIndex].totalAmount;
      inStockList[orderIndex].remainingAmount = 0;
      inStockList[orderIndex].isPaid = "已支付";

      uni.showToast({
        title: "已标记为已支付",
        icon: "success",
      });
    }
  } catch (error) {
    console.error("标记已付款失败:", error);
    uni.showToast({
      title: "操作失败",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
}

// 跳转订单详情
function goToDetails(id) {
  uni.navigateTo({
    url: `/pages/inStock/inStockAddDetails/index?type=details&id=${id}`,
  });
}
</script>

<style>
.container {
  padding: 10px;
}
.header {
  margin-bottom: 15px;
}
.title {
  font-size: 18px;
  font-weight: bold;
}
.stock-info-card {
  padding: 5px;
}
.stock-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.section-title {
  font-size: 16px;
  font-weight: bold;
}
.stock-status {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}
.status-normal {
  background-color: #e1f3d8;
  color: #67c23a;
}
.status-alert {
  background-color: #fdf6ec;
  color: #e6a23c;
}
.status-shortage {
  background-color: #fef0f0;
  color: #f56c6c;
}
.stock-details {
  padding: 5px 0;
}
.info-row {
  display: flex;
  margin-bottom: 8px;
}
.info-label {
  width: 80px;
  color: #666;
}
.info-value {
  flex: 1;
}
.form-section {
  padding: 5px;
}
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.form-label {
  width: 80px;
  color: #666;
}
.form-input {
  flex: 1;
  height: 35px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
}
.unit-text {
  margin-left: 10px;
  color: #666;
}
.submit-btn {
  background-color: #2979ff;
  color: white;
  margin-top: 20px;
}

/* 新增样式 - 入库订单列表区域 */
.order-list-section {
  margin-top: 20px;
}
.section-header {
  margin-bottom: 10px;
}
.filter-area {
  border-radius: 5px;
  margin-bottom: 15px;
}
.filter-group {
  margin-bottom: 12px;
}
.filter-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}
.date-range,
.price-range {
  display: flex;
  align-items: center;
}
.picker-text {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 120px;
  text-align: center;
  background-color: #fff;
}
.date-separator,
.range-separator {
  margin: 0 10px;
  color: #999;
}
.price-input {
  flex: 1;
  height: 36px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
  background-color: #fff;
}
.filter-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}
.filter-btn,
.reset-btn {
  flex: 1;
  margin: 0 5px;
  font-size: 14px;
  padding: 8px 0;
}
.filter-btn {
  background-color: #2979ff;
  color: #fff;
}
.reset-btn {
  background-color: #f2f2f2;
  color: #666;
}
.order-item {
  padding: 5px 0;
}
.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.order-date {
  font-weight: bold;
}
.order-price {
  color: #f56c6c;
  font-weight: bold;
}
.order-content {
  border-top: 1px solid #eee;
  padding-top: 10px;
}
.order-info {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}
.info-item {
  margin-right: 15px;
  color: #666;
}
.order-remark {
  font-size: 14px;
  color: #999;
}
.empty-tip {
  text-align: center;
  padding: 20px;
  color: #999;
}

/* 添加下拉刷新相关样式 */
.refresh-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px;
  width: 100%;
}

.loading-icon {
  width: 20px;
  height: 20px;
  border: 2px solid #2979ff;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 0.8s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 调整订单列表区域 */
.order-list-scroll {
  width: 100%;
  /* height设置为动态计算值 */
}

/* 加载更多样式 */
.load-more {
  text-align: center;
  padding: 15px 0;
}

.loading-text,
.no-more-text {
  color: #999;
  font-size: 14px;
}

.no-more-text {
  color: #ccc;
}

/* 添加商品信息样式 */
.product-info {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 10px;
}
.product-name {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}
.product-spec {
  margin-left: 15px;
  color: #666;
  background-color: #f0f0f0;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 14px;
}

/* 添加支付相关样式 */
.order-tabs {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
  border-radius: 10px;
  overflow: hidden;
  background-color: #f2f2f2;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 14px;
  color: #666;
  transition: all 0.3s;
}

.tab-item.active {
  background-color: #2979ff;
  color: #fff;
  font-weight: 500;
}

.action-buttons-row {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.pay-btn,
.mark-btn {
  font-size: 12px;
  padding: 5px 10px;
}

.pay-btn {
  background-color: #2979ff;
  color: white;
}

.mark-btn {
  background-color: #67c23a;
  color: white;
}

/* 付款对话框样式 */
.payment-dialog {
  padding: 10px 0;
}

.dialog-title {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 10px;
}

.payment-summary {
  margin-bottom: 15px;
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 4px;
}

.summary-item {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
}

.highlight {
  color: #f56c6c;
  font-weight: bold;
}

.payment-input-area {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.payment-label {
  width: 80px;
  color: #333;
}

.payment-input {
  flex: 1;
  height: 35px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
}

.dialog-buttons {
  display: flex;
  justify-content: space-between;
}

.cancel-btn,
.confirm-btn {
  width: 45%;
  padding: 8px 0;
  font-size: 14px;
}

.cancel-btn {
  background-color: #f2f2f2;
  color: #666;
}

.confirm-btn {
  background-color: #2979ff;
  color: white;
}

/* 支付信息样式 */
.payment-info {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.payment-item {
  margin-right: 15px;
  color: #666;
}

.remaining-amount {
  font-weight: 500;
  color: #f56c6c;
}

.amount-zero {
  color: #67c23a;
}

/* 调试信息样式 */
.debug-info {
  padding: 10px;
  margin: 10px;
  border: 1px solid #ccc;
  background: #f8f8f8;
}
</style>
